package com.loong.musicdemo;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.FragmentContainerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.loong.musicdemo.model.User;
import com.loong.musicdemo.util.httpUtil.HttpUtil;

import org.json.JSONException;
import org.json.JSONObject;

import de.hdodenhof.circleimageview.CircleImageView;

public class AccountMyCenter extends AppCompatActivity {
    private CoordinatorLayout bcgImg;//背景图片
    private CircleImageView titleIcon;//头像
    private TextView nickName;//昵称
    private TextView follows;//关注数
    private TextView followeds;//粉丝数
    private User user;//用于存储当前用户信息
    private String bcgUrl;//背景图片地址
    private String avatarUrl;//头像地址
    private FragmentContainerView myCenter;
    private FragmentContainerView myDynamic;
    private AppBarLayout appBar;
    private RelativeLayout userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_my_center);
        //背景图片融合
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);//若工具栏可用,则显示Home菜单
        }
        initView();//初始化布局
        new ProfileUpdate().execute();//处理网络请求数据
    }


    /**
     * 初始化布局
     */
    private void initView() {
        bcgImg = findViewById(R.id.bcgImg);
        titleIcon = findViewById(R.id.title_ico);
        nickName = findViewById(R.id.nickname);
        follows = findViewById(R.id.follows);
        followeds = findViewById(R.id.followeds);
        myCenter = findViewById(R.id.my_center);
        myDynamic = findViewById(R.id.my_dynamic);
        appBar = findViewById(R.id.app_bar);
        userInfo = findViewById(R.id.userinfo);
        //选项卡
        //选项卡
        TabLayout tabLayout = findViewById(R.id.tab_layout);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (TextUtils.equals(tab.getText(), "动态")) {
                    myCenter.setVisibility(View.GONE);
                    myDynamic.setVisibility(View.VISIBLE);
                } else if (TextUtils.equals(tab.getText(), "主页")) {
                    myCenter.setVisibility(View.VISIBLE);
                    myDynamic.setVisibility(View.GONE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        //编辑个人资料
        findViewById(R.id.edit).setOnClickListener(v -> {

        });
        //更滑背景图片
        findViewById(R.id.change_bcg).setOnClickListener(v -> {

        });
        //实现上画结束后不显示背景信息
        appBar.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            if (verticalOffset == 0) {
                userInfo.setVisibility(View.VISIBLE);
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                //折叠状态
                userInfo.setVisibility(View.GONE);
            }
        });
    }


    /**
     * 获取用户信息并刷新
     */
    @SuppressLint("StaticFieldLeak")
    class ProfileUpdate extends AsyncTask<User, Void, User> {
        @Override
        protected void onPreExecute() {//执行过程中,隐藏对应视图
            super.onPreExecute();
            //显示进度条时,隐藏数据栏
            titleIcon.setVisibility(View.GONE);
            nickName.setVisibility(View.GONE);
            follows.setVisibility(View.GONE);
            followeds.setVisibility(View.GONE);
        }

        @Override
        protected User doInBackground(User... users) {
            SharedPreferences userInfo = getSharedPreferences("userInfo", MODE_PRIVATE);
            String userId = userInfo.getString("userId", null);
            String host = getResources().getString(R.string.host);
            String responseBody = HttpUtil.sendReturnOKHttpRequest(host + "/user/detail?uid=" + userId);//获取用户信息,返回HTTP响应体
            user = new User();
            try {
                if (responseBody != null) {
                    JSONObject object = new JSONObject(responseBody);
                    user.setLevel(object.getInt("level"));
                    user.setListenSongs(object.getInt("listenSongs"));
                    JSONObject profile = object.getJSONObject("profile");
                    user.setNickName(profile.getString("nickname"));
                    user.setFollows(profile.getInt("follows"));
                    user.setFollowed(profile.getInt("followeds"));
                    bcgUrl = profile.getString("backgroundUrl");
                    avatarUrl = profile.getString("avatarUrl");
                    return user;
                } else return null;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onPostExecute(User user) {
            super.onPostExecute(user);
            if (user != null) {
                SharedPreferences userInfo = getSharedPreferences("userInfo", MODE_PRIVATE);
                SharedPreferences.Editor editor = userInfo.edit();
                editor.putInt("level", user.getLevel());
                editor.putInt("listenSongs", user.getListenSongs());
                editor.apply();//提交信息
                nickName.setText(user.getNickName());
                follows.setText(Integer.toString(user.getFollows()));
                followeds.setText(Integer.toString(user.getFollowed()));
            } else {
                Toast.makeText(AccountMyCenter.this, "用户信息获取失败,请检查网络!", Toast.LENGTH_SHORT).show();
            }
            Glide.with(AccountMyCenter.this).load(avatarUrl).into(titleIcon);//加载头像
            Glide.with(AccountMyCenter.this).load(bcgUrl).into(new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                    bcgImg.setBackground(resource);
                }
            });
            //操作结束后,显示
            titleIcon.setVisibility(View.VISIBLE);
            nickName.setVisibility(View.VISIBLE);
            follows.setVisibility(View.VISIBLE);
            followeds.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示返回菜单栏
     *
     * @param item item
     * @return item
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;//返回前一个活动
        }
        return super.onOptionsItemSelected(item);
    }
}
